package com.bdy.lm.taximanager.ui;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bdy.lm.taximanager.R;
import com.bdy.lm.taximanager.app.MyApp;
import com.bdy.lm.taximanager.http.HttpImage;
import com.bdy.lm.taximanager.http.HttpJson;
import com.bdy.lm.taximanager.model.Fare;
import com.bdy.lm.taximanager.model.LocationTrack;
import com.bdy.lm.taximanager.model.DriverInfo;
import com.bdy.lm.taximanager.model.MessagePackaging;
import com.bdy.lm.taximanager.model.RunningTaximeterState;
import com.bdy.lm.taximanager.model.SerialPortData;
import com.bdy.lm.taximanager.model.ServerCommandEvent;
import com.bdy.lm.taximanager.model.Taxi;
import com.bdy.lm.taximanager.port.TaxiMeterDataAnalysis;
import com.bdy.lm.taximanager.rfid.RFIDCallback;
import com.bdy.lm.taximanager.rfid.TotalManager;
import com.bdy.lm.taximanager.service.MyService;
import com.bdy.lm.taximanager.thread.ModifyFareThread;
import com.bdy.lm.taximanager.thread.VerifyAdjustThread;
import com.bdy.lm.taximanager.util.FileUtils;
import com.bdy.lm.taximanager.util.TimeUtils;
import com.bdy.lm.taximanager.util.JsonUtils;
import com.bdy.lm.taximanager.util.ToastUtils;
import com.bdy.lm.taximanager.view.AutoVerticalScrollTextView;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android_serialport_api.SerialPort;
import de.greenrobot.event.EventBus;

public class MainActivity extends AppCompatActivity implements RFIDCallback, NavigationView.OnNavigationItemSelectedListener, TaxiMeterDataAnalysis.PassTransitionInfo, TaxiMeterDataAnalysis.LocalQueryLicense {

    private TextView money, price, length, time, companyName, driverName, licenseNum, cardNum, inTime, telephone, message, isNight, twoOrOne, ic, stop, low, upTime, downTime;
    private TextView thankEvaluate;
    private Camera camera;
    private DriverInfo driverInfo;
    private SharedPreferences.Editor editor;
    private Handler handler;
    private HttpJson httpJson = new HttpJson();
    private String id = null;
    private ImageView imageView;
    private boolean isSuccess = false;
    private MediaRecorder mRecorder;//录音
    private MediaRecorder mediaRecorder;//录像
    private MessagePackaging messagePackaging = new MessagePackaging(102);
    private Camera.Parameters parameters;
    private SharedPreferences sharedPreferences;
    private File soundFile;
    private SurfaceView surfaceViewPhoto, surfaceViewVideo;
    public Thread signOutThread, recordVideoThread, getDriverPhotoThread;
    private Runnable recordTrack, takePhotoThread, initTaxiInfo;
    private int videoTime = 0, i = 1;
    private int number =0;
    private boolean isRunning=true, beginRecordTrack = true;
    private AutoVerticalScrollTextView verticalScrollTV;
    private Logger logger;
    public static final String TRANSACTION_INFO = "TransactionInfo";
    private RunningTaximeterState state;
    private String license = "";
    private DecimalFormat df = new DecimalFormat("######0.00");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        VerifyAdjustThread.getInstance();
        //初始化串口调用
        TaxiMeterDataAnalysis.newInstance().setPassTransitionInfoCallBack(this);
        //System.out.println("device" + Arrays.toString(new SerialPortFinder().getAllDevices()));
        TaxiMeterDataAnalysis.newInstance().setLocalQueryLicense(this);
        //更新运价信息
        new ModifyFareThread().start();

        sharedPreferences = getSharedPreferences(DriverInfo.getDriverInfo().getICID(), Context.MODE_PRIVATE);
        driverInfo = DriverInfo.getDriverInfo();
        TotalManager.instance().setRFIDCallback(this);
        EventBus.getDefault().register(this);

        initThread();
        setTextView();
        logger = Logger.getLogger(this.getClass());
        initTaxiInfo();

        //启动服务
        startService(new Intent(this, MyService.class));

        handler = new Handler() {
            public void handleMessage(Message msg) {
                if (msg.what == 101) {
                    signOut();
                } else if(msg.what == 102) {
                    alert("身份错误，请核实后重新刷卡！");
                } else if(msg.what == 103) {
                    imageView.setImageBitmap(HttpImage.getReceivedBitmap());
                } else if(msg.what == 104) {
                    surfaceViewVideo.setVisibility(View.INVISIBLE);
                } else if(msg.what == 105) {
                    surfaceViewPhoto.setVisibility(View.INVISIBLE);
                } else if(msg.what == 106) {
                    startActivity(new Intent(MainActivity.this, LoginActivity.class));
                } else if(msg.what == 107) {//交易结束
                    //isNight.setText(TimeUtils.isNight());
                    //stop.setText("暂停");
                    money.setText(df.format(transitionData.getSum()));
                    price.setText(df.format(transitionData.getPrice()));
                    length.setText(df.format(transitionData.getDistance()));
                    downTime.setText(transitionData.getDown());
                    thankEvaluate.setVisibility(View.VISIBLE);
                    noEvaluate();
                    //startActivityForResult(new Intent(MainActivity.this, EvaluateActivity.class), 1000);
                } else if(msg.what == 108) {//交易开始
                    isNight.setText(TimeUtils.isNight());
                    stop.setText("");
                    money.setText("");
                    price.setText("");
                    length.setText("");
                    time.setText("00:00:00");
                    upTime.setText(getupData.getUp());
                    downTime.setText("");
                } else if (msg.what == 109) {
                    alert("上传失败，请检查网络！！");
                } else if (msg.what == 110) {
                    thankEvaluate.setVisibility(View.INVISIBLE);
                } else if (msg.what == 111) {
                    thankEvaluate.setText("感谢您的评价！");
                } else if (msg.what == 112) {
                    licenseNum.setText(license);
                } else if(msg.what == 199) {
                    verticalScrollTV.next();
                    number++;
                    Map<String, String> one = driverInfo.getMsgList().get(number % driverInfo.getMsgList().size());
                    String reMsg = one.get("content") + "\n发布时间：" + one.get("date");
                    verticalScrollTV.setText(reMsg);//strings[number%strings.length]
                } else if(msg.what == 200) {
                    isNight.setText(state.getTaximeterState()[7]);
                    if (state.getTaximeterState()[5].equals("")) {
                        twoOrOne.setText(state.getTaximeterState()[6]);
                        SerialPortData.getInstance().getTransitionData().setRunState("double");
                    } else {
                        twoOrOne.setText(state.getTaximeterState()[5]);
                        SerialPortData.getInstance().getTransitionData().setRunState("single");
                    }
                    ic.setText(state.getTaximeterState()[4]);
                    stop.setText(state.getTaximeterState()[3]);
                    low.setText(state.getTaximeterState()[0]);
                    price.setText(df.format(state.getPrice()));
                    length.setText(df.format(state.getMeters()));
                    money.setText(df.format(state.getMoney()));
                    time.setText("" + state.getWaiting()[0] + ":" + state.getWaiting()[1] + ":" + state.getWaiting()[2]);
                }
            }
        };

        Map<String, String> msg = new HashMap<>();
        msg.put("title", "消息测试");
        msg.put("date", TimeUtils.getFormatTime());
        msg.put("content", "这是一条测试信息！");
        driverInfo.setMsgList(msg);

        TaxiMeterDataAnalysis.newInstance().getMeterPoint(TaxiMeterDataAnalysis.TAXI_INFO);

        final String d = "{\"messageID\":114,\"messageSerialNum\":386,\"flagBitBegin\":126,\"ISUFlag\":\"1616010526880\",\"checkCode\":-34,\"flagBitEnd\":126,\"messageSize\":15,\"locationTracks\":[{\"speed\":10.048649,\"time\":1513478297112,\"longitude\":119.267058,\"latitude\":26.056903},{\"speed\":10.086487,\"time\":1513478298113,\"longitude\":119.267145,\"latitude\":26.056863},{\"speed\":10.2,\"time\":1513478299113,\"longitude\":119.267232,\"latitude\":26.056825},{\"speed\":10.064865,\"time\":1513478300114,\"longitude\":119.26732,\"latitude\":26.056785},{\"speed\":10.064865,\"time\":1513478301114,\"longitude\":119.26732,\"latitude\":26.056785},{\"speed\":10.151351,\"time\":1513478302115,\"longitude\":119.267408,\"latitude\":26.056745},{\"speed\":10.151351,\"time\":1513478303115,\"longitude\":119.267497,\"latitude\":26.056707},{\"speed\":10.135135,\"time\":1513478304116,\"longitude\":119.267668,\"latitude\":26.056627},{\"speed\":10.135135,\"time\":1513478305117,\"longitude\":119.267668,\"latitude\":26.056627},{\"speed\":9.94054,\"time\":1513478306117,\"longitude\":119.267747,\"latitude\":26.056588},{\"speed\":9.475676,\"time\":1513478307117,\"longitude\":119.267825,\"latitude\":26.056552},{\"speed\":8.929729,\"time\":1513478308118,\"longitude\":119.267975,\"latitude\":26.05648},{\"speed\":8.929729,\"time\":1513478309118,\"longitude\":119.267975,\"latitude\":26.05648},{\"speed\":9.021622,\"time\":1513478310119,\"longitude\":119.268125,\"latitude\":26.056413},{\"speed\":9.021622,\"time\":1513478311120,\"longitude\":119.268125,\"latitude\":26.056413},{\"speed\":9,\"time\":1513478312120,\"longitude\":119.268202,\"latitude\":26.05638},{\"speed\":8.848649,\"time\":1513478313120,\"longitude\":119.268278,\"latitude\":26.056345},{\"speed\":9,\"time\":1513478314121,\"longitude\":119.268355,\"latitude\":26.05631},{\"speed\":9.335135,\"time\":1513478315121,\"longitude\":119.268512,\"latitude\":26.056235},{\"speed\":9.524324,\"time\":1513478316122,\"longitude\":119.268593,\"latitude\":26.056197},{\"speed\":9.524324,\"time\":1513478317122,\"longitude\":119.268593,\"latitude\":26.056197},{\"speed\":9.735135,\"time\":1513478318123,\"longitude\":119.26868,\"latitude\":26.056158},{\"speed\":10.41081,\"time\":1513478319123,\"longitude\":119.268862,\"latitude\":26.056077},{\"speed\":10.41081,\"time\":1513478320124,\"longitude\":119.268862,\"latitude\":26.056077},{\"speed\":10.902702,\"time\":1513478321125,\"longitude\":119.269048,\"latitude\":26.05599},{\"speed\":11.097298,\"time\":1513478322125,\"longitude\":119.269142,\"latitude\":26.055945},{\"speed\":11.151351,\"time\":1513478323126,\"longitude\":119.269237,\"latitude\":26.055902},{\"speed\":11.135135,\"time\":1513478324127,\"longitude\":119.269328,\"latitude\":26.05586},{\"speed\":10.891891,\"time\":1513478325127,\"longitude\":119.269418,\"latitude\":26.055818},{\"speed\":10.691892,\"time\":1513478326128,\"longitude\":119.269507,\"latitude\":26.055778},{\"speed\":10.513514,\"time\":1513478327128,\"longitude\":119.269595,\"latitude\":26.055738},{\"speed\":10.427027,\"time\":1513478328128,\"longitude\":119.269682,\"latitude\":26.055698},{\"speed\":10.281081,\"time\":1513478329129,\"longitude\":119.269767,\"latitude\":26.055655},{\"speed\":10.113514,\"time\":1513478330129,\"longitude\":119.269848,\"latitude\":26.055613},{\"speed\":9.951351,\"time\":1513478331130,\"longitude\":119.26993,\"latitude\":26.055572},{\"speed\":9.951351,\"time\":1513478332131,\"longitude\":119.26993,\"latitude\":26.055572},{\"speed\":9.848649,\"time\":1513478333132,\"longitude\":119.270097,\"latitude\":26.055497},{\"speed\":9.810811,\"time\":1513478334132,\"longitude\":119.27018,\"latitude\":26.05546},{\"speed\":9.827027,\"time\":1513478335133,\"longitude\":119.270263,\"latitude\":26.055422},{\"speed\":9.897297,\"time\":1513478336133,\"longitude\":119.270348,\"latitude\":26.055382},{\"speed\":10.048649,\"time\":1513478337134,\"longitude\":119.270433,\"latitude\":26.05534},{\"speed\":10.221622,\"time\":1513478338134,\"longitude\":119.270522,\"latitude\":26.055298},{\"speed\":10.378378,\"time\":1513478339135,\"longitude\":119.27061,\"latitude\":26.055258},{\"speed\":10.52973,\"time\":1513478340135,\"longitude\":119.270702,\"latitude\":26.055217},{\"speed\":10.648648,\"time\":1513478341135,\"longitude\":119.270792,\"latitude\":26.055175},{\"speed\":10.832433,\"time\":1513478342136,\"longitude\":119.270885,\"latitude\":26.055132},{\"speed\":10.908108,\"time\":1513478343137,\"longitude\":119.270978,\"latitude\":26.055088},{\"speed\":10.85946,\"time\":1513478344137,\"longitude\":119.271072,\"latitude\":26.055047},{\"speed\":10.891891,\"time\":1513478345138,\"longitude\":119.271165,\"latitude\":26.055003},{\"speed\":10.875675,\"time\":1513478346138,\"longitude\":119.271258,\"latitude\":26.054962},{\"speed\":11,\"time\":1513478347138,\"longitude\":119.271352,\"latitude\":26.05492},{\"speed\":11.016216,\"time\":1513478348139,\"longitude\":119.271443,\"latitude\":26.054877},{\"speed\":11.070271,\"time\":1513478349139,\"longitude\":119.271537,\"latitude\":26.054833},{\"speed\":11.081081,\"time\":1513478350140,\"longitude\":119.27163,\"latitude\":26.05479},{\"speed\":11.086487,\"time\":1513478351140,\"longitude\":119.271723,\"latitude\":26.054748},{\"speed\":11.005405,\"time\":1513478352140,\"longitude\":119.271818,\"latitude\":26.054703},{\"speed\":11.05946,\"time\":1513478353141,\"longitude\":119.271913,\"latitude\":26.054662},{\"speed\":11.048649,\"time\":1513478354141,\"longitude\":119.272008,\"latitude\":26.054622},{\"speed\":11.010811,\"time\":1513478355142,\"longitude\":119.272102,\"latitude\":26.054582},{\"speed\":10.929729,\"time\":1513478356142,\"longitude\":119.272195,\"latitude\":26.05454},{\"speed\":10.85946,\"time\":1513478357143,\"longitude\":119.272287,\"latitude\":26.0545},{\"speed\":10.778378,\"time\":1513478358143,\"longitude\":119.272378,\"latitude\":26.054458},{\"speed\":10.713513,\"time\":1513478359144,\"longitude\":119.272468,\"latitude\":26.054417},{\"speed\":10.583784,\"time\":1513478360144,\"longitude\":119.272557,\"latitude\":26.054373},{\"speed\":10.632432,\"time\":1513478361144,\"longitude\":119.272647,\"latitude\":26.05433},{\"speed\":10.654054,\"time\":1513478362145,\"longitude\":119.272735,\"latitude\":26.054287},{\"speed\":10.508108,\"time\":1513478363145,\"longitude\":119.272822,\"latitude\":26.054243},{\"speed\":10.545946,\"time\":1513478364146,\"longitude\":119.27291,\"latitude\":26.0542},{\"speed\":10.52973,\"time\":1513478365146,\"longitude\":119.273,\"latitude\":26.05416}],\"carMeasure\":{\"isRegular\":\"708.6 -1.0\",\"Alongitude\":119.266975,\"Aaltitude\":21.2,\"ScarMeasure\":0,\"Baltitude\":19,\"Bspeed\":10.497297,\"Blongtitde\":119.27309,\"Alatitude\":26.056943,\"Aspeed\":9.929729,\"Blatitude\":26.054123}}";
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    HttpJson httpJson = new HttpJson();
                    while (true) {
                        //httpJson.HttpJsonPost(JsonUtils.stringToJsonObject(d), MyApp.serverUrl);
                        delay(2000);
                        //Log.d("Main", "经度：" + MyApp.locationMessageBody.getLongitude() + " 纬度：" + MyApp.locationMessageBody.getLatitude());
                        //System.out.println(httpJson.getPostJson());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    @Override
    public void passLicense(String license) {
        this.license = license;
        handler.sendEmptyMessage(112);
    }

    private void initTaxiInfo(){
        final SharedPreferences sp = getSharedPreferences(SettingActivity.TAXI_INFO_SP, Context.MODE_PRIVATE);
        final SharedPreferences.Editor editor = sp.edit();
        if (sp.contains(SettingActivity.ALL_INFO)) {
            MyApp.taxi = JsonUtils.gson.fromJson(sp.getString(SettingActivity.ALL_INFO, ""), Taxi.class);
        } else {
            executors.execute(new Runnable() {
                @Override
                public void run() {
                    JSONObject jo = JsonUtils.mapToJsonObject(new MessagePackaging(116).getHeartBitMessagePackageMap());
                    HttpJson http = new HttpJson();
                    while (true) {
                        if (http.getPostJson() == null) {
                            http.HttpJsonPost(jo, MyApp.serverUrl);
                        } else {
                            String taxi = http.getPostJson().toString();
                            MyApp.taxi = JsonUtils.gson.fromJson(taxi, Taxi.class);
                            editor.putString(SettingActivity.ALL_INFO, taxi);
                            editor.commit();
                            break;
                        }
                        delay(2000);
                    }
                }
            });
        }
    }


    /**
     *  初始化线程，签退，拍照，录像，获取出租车司机头像照片
     */
    private void initThread() {

        signOutThread = new Thread(new Runnable() {
            public void run() {
                while (!isSuccess) {
                    delay(100);
                    id = driverInfo.getICID();
                    if (id != null) {
                        if (id.equals(driverInfo.getICID())) {
                            handler.sendEmptyMessage(101);
                            isSuccess = true;
                        } else {
                            handler.sendEmptyMessage(102);
                            id = null;
                        }
                    }
                }
            }
        });

        takePhotoThread = new Runnable() {
            @Override
            public void run() {
                delay(5000);//为了错开两次相同指令
                if (camera != null) {
                    System.out.println("拍照camera不为空");
                    camera.takePicture(null, null, new MyPictureCallback());
                }
                delay(3000);
                handler.sendEmptyMessage(105);
            }
        };

        recordVideoThread = new Thread(new Runnable() {
            @Override
            public void run() {
                delay(3000);
                if (videoTime > 0) {
                    startVideo();
                }
                delay(videoTime * 1000);
                stopVideo();
                handler.sendEmptyMessage(104);
            }
        });
        getDriverPhotoThread = new Thread(new Runnable() {
            @Override
            public void run() {
                HttpImage.httpImageGet(MainActivity.this, driverInfo.getICID());
                while (HttpImage.getReceivedBitmap() == null) {
                    delay(500);
                    HttpImage.httpImageGet(MainActivity.this, driverInfo.getICID());
                }
                handler.sendEmptyMessage(103);
                Log.d("HttpImage", "大小：" + HttpImage.getReceivedBitmap().getByteCount());
                FileUtils.saveDriverPhoto(HttpImage.getReceivedBitmap(), driverInfo.getICID());
            }
        });

        //每隔15秒切换一条消息
        new Thread() {
            @Override
            public void run() {
                while (isRunning){
                    delay(15000);
                    handler.sendEmptyMessage(199);
                }
            }
        }.start();

        recordTrack = new Runnable() {
            @Override
            public void run() {
                List<LocationTrack> locationTracks = new ArrayList<>();

                while(beginRecordTrack) {//隔两秒记录一次
                    delay(2000);
                    locationTracks.add(new LocationTrack(MyApp.locationMessageBody.getLongitude(), MyApp.locationMessageBody.getLatitude(),
                                                       MyApp.locationMessageBody.getSpeed(), TimeUtils.getStampTime()));
                }
                //记录完成后保存
                SerialPortData.getInstance().getTransitionData().setLocationTracks(locationTracks);
            }
        };
    }

    /**
     * 传递重车过程中计价器的状态信息
     * @param state
     */
    @Override
    public void passRunningState(RunningTaximeterState state) {
        this.state = state;
        handler.sendEmptyMessage(200);
    }

    /**
     * 处理评价Activity返回的信息
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1000 && resultCode == RESULT_OK) {
//            Log.d("uploadTransitionData", "" + uploadTransitionData.isAlive());
//            if (!uploadTransitionData.isAlive()) {
//                Log.d("uploadTransitionData", "" + uploadTransitionData.isAlive());
//                uploadTransitionData.start();
//            }
            //executors.execute(uploadTransitionData);
            //Log.d("onActivityResult", "接收到");
        }
    }
    private ExecutorService executors = Executors.newFixedThreadPool(5);

    private SerialPortData.GetupData getupData;

    /**
     *  交易开始，串口数据回调，得到上车信息
     * @param getupData
     */
    @Override
    public void passGetupInfo(SerialPortData.GetupData getupData) {
        this.getupData = getupData;
        handler.sendEmptyMessage(108);
        MyApp.runState = "working";
        System.out.println("transitionNum" + MyApp.transitionNum);
        logger.info("transitionNum" + MyApp.transitionNum);
        beginRecordTrack = true;//开始记录轨迹
        executors.execute(recordTrack);
    }

    private SerialPortData.TransitionData transitionData;
    /**
     *  交易结束，串口数据回调函数，得到串口交易信息
     * @param transitionData 交易数据
     */
    @Override
    public void passTransitionInfo(SerialPortData.TransitionData transitionData) {
        this.transitionData = transitionData;
        MyApp.transitionNum = transitionData.getCurrentRunTime();
        MyApp.runState = "none";
        beginRecordTrack = false;//停止记录轨迹
        handler.sendEmptyMessage(107);//打开评价界面
    }
    //上传交易数据
    private Runnable uploadTransitionData = new Runnable() {
        @Override
        public void run() {
            try {
                JSONObject jo = JsonUtils.stringToJsonObject(JsonUtils.toGson(new MessagePackaging(110).getTransactionMessagePackageMap(SerialPortData.getInstance().getTransitionData().getTransInfo())));
                System.out.println("交易数据JSON" + jo.toString());
                boolean flag = true;
                int totalTime = 15;
                System.out.println("upload开始");
                while (flag) {
                    if (totalTime > 0) {//每隔一秒上传一次，共15次
                        if (httpJson.getPostJson() == null) {
                            httpJson.HttpJsonPost(jo, MyApp.serverUrl);
                        } else {//上传成功，收到回复后
                            if (httpJson.getPostJson().getString("flag").equals("failure")) {//服务器出错
                                //System.out.println("upload服务器出错");
                                logger.error("upload服务器出错");
                                httpJson.setPostJson(null);//继续上传
                            } else if (httpJson.getPostJson().getString("flag").equals("success")){//上传成功，停止循环
                                //System.out.println("upload成功");
                                logger.info("upload成功");
                                flag = false;
                                httpJson.setPostJson(null);
                            }

                        }
                        System.out.println("upload");
                        totalTime--;
                        delay(2000);
                    } else {//上传15次后不成功，停止循环，保存交易数据到本地
                        flag = false;
                        String ti = JsonUtils.toGson(SerialPortData.getInstance().getTransitionData().getTransInfo());
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        String timeSum, currentTime = TimeUtils.getStampTimeString();
                        if(sharedPreferences.contains(TRANSACTION_INFO)) {
                            timeSum = sharedPreferences.getString(TRANSACTION_INFO, null) + " " + currentTime;
                        } else {
                            timeSum = TimeUtils.getStampTimeString();
                        }
                        editor.putString(TRANSACTION_INFO, timeSum);
                        editor.putString(currentTime, ti);
                        editor.commit();
                        logger.info("交易信息上传失败，保存本地：" + ti);
                        handler.sendEmptyMessage(109);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                logger.error("Json异常：" + e);
            }
        }
    };
    /**
     *  检测按键事件
     * @param keyCode
     * @param keyEvent
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
        if (keyCode == 4) {//
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
        }
        if (keyCode == 8) {//呼叫中心
            dial("123456789");
        }
        if (keyCode == 16) {
            hasEvaluate("satisfaction");
        } else if (keyCode == 15) {
            hasEvaluate("ordinary");
        } else if (keyCode == 14) {
            hasEvaluate("dissatisfaction");
        }
        return true;
    }
    private void hasEvaluate(String evaluate){
        SerialPortData.getInstance().getTransitionData().setEvaluate(evaluate);
        executors.execute(uploadTransitionData);
        handler.sendEmptyMessage(111);//感谢评价
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(110);//设置为不可见
            }
        }, 1000);
    }
    private void noEvaluate(){
        //Log.d("EvaluateActivity", SerialPortData.getInstance().getTransitionData().toString());
        MyApp.transitionNum = SerialPortData.getInstance().getTransitionData().getCurrentRunTime();
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(110);//设置为不可见
                SerialPortData.getInstance().getTransitionData().setEvaluate("null");
                executors.execute(uploadTransitionData);
            }
        }, 10000);
    }
    /**
     *  回调函数，接收传过来的IC卡号
     * @param id IC卡号
     */
    @Override
    public void processCardID(String id) {
        this.id = id;
        Log.d("thisID", id);
    }

    /**
     *  产生右上角菜单，用作签退
     * @param menu
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    /**
     *  右上角菜单点击事件响应函数
     * @param item 点击的选项
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            exitApp("请确定后刷卡签退！");
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     *  响应导航菜单点击事件
     * @param item 点击的选项
     * @return
     */
    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        //Handle navigation view item clicks here.
        int id = item.getItemId();
        if (id == R.id.price_query) {
            Intent i = new Intent(MainActivity.this, SerialActivity.class);
            startActivity(i);
        } else if (id == R.id.calling_managment) {
            dial("1234567890");
        } else if (id == R.id.message) {
            Intent intent = new Intent(MainActivity.this, MessageListActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("msgList", (Serializable) driverInfo.getMsgList());
            intent.putExtras(bundle);
            startActivity(intent);
        } else if (id == R.id.photo) {
            startActivity(new Intent(MainActivity.this, CameraActivity.class));
        } else if (id == R.id.sound) {
            //录音
        } else if (id == R.id.taxi_info) {
            startActivity(new Intent(MainActivity.this, TaxiInfoActivity.class));
        } else if (id == R.id.open_map) {
            //Intent intent = new Intent();
            //intent.setData(Uri.parse("baidumap://map/show?center=40.057406655722,116.29644071728&zoom=11&traffic=on&bounds=37.8608310000,112.5963090000,42.1942670000,118.9491260000"));
            //startActivity(intent);
            try{
                PackageManager packageManager = this.getPackageManager();
                Intent intent = packageManager.getLaunchIntentForPackage("com.baidu.BaiduMap");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            } catch (NullPointerException e){
                Toast t = Toast.makeText(this, "还没有安装百度地图！！！", Toast.LENGTH_LONG);
                t.setGravity(Gravity.CENTER, 0, 0);
                t.show();
            }
        } else if (id == R.id.system_setup) {
            startActivity(new Intent(MainActivity.this, SettingActivity.class));
        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    /**
     *  签退事件提示
     * @param s 提示信息
     */
    private void exitApp(String s) {
        new AlertDialog.Builder(this).setTitle("提示：").setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int i) {
                id = null;
                if (!signOutThread.isAlive()) {
                    signOutThread.start();
                }
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt) {
            }
        }).setMessage(s).create().show();
    }

    /**
     *  签退
     */
    private void signOut() {
        final ProgressDialog localProgressDialog = new ProgressDialog(this, R.style.AppTheme_Dark_Dialo);
        localProgressDialog.setIndeterminate(true);
        localProgressDialog.setMessage("已识别，正在签退...");
        localProgressDialog.show();
        localProgressDialog.setCanceledOnTouchOutside(false);
        new Thread(new Runnable() {
            public void run() {
                editor = sharedPreferences.edit();
                editor.remove(id + "签到时间");
                editor.remove(id + "签退时间");
                editor.putString(id + "签退时间", TimeUtils.getInOutTime());
                editor.commit();
                JSONObject msg = JsonUtils.mapToJsonObject(messagePackaging.getSignOutMessageMap(driverInfo.getICID()));
                while (httpJson.getPostJson() == null) {
                    delay(1000);
                    System.out.println("刷卡签退");
                    httpJson.HttpJsonPost(msg, MyApp.serverUrl);//提交请求
                }
                MyApp.threadRun = false;
                DriverInfo.getDriverInfo().resetFields();
                localProgressDialog.dismiss();
                handler.sendEmptyMessage(106);
            }
        }).start();
    }

    /**
     *  接收 查询服务器指令线程 解析得到的指令
     * @param receivedMessageEvent 收到的服务器指令
     */
    public void onEventMainThread(ServerCommandEvent receivedMessageEvent) {
        if (!receivedMessageEvent.getReceivedMessage().equals("haha")) {
            Map<String, String> msg = new HashMap<>();
            msg.put("title", "新增第" + i + "条信息");
            msg.put("date", TimeUtils.getFormatTime());
            msg.put("content", receivedMessageEvent.getReceivedMessage());
            driverInfo.setMsgList(msg);
            i++;
            verticalScrollTV.setText(receivedMessageEvent.getReceivedMessage());
            //Log.d("MainActivity", "新增"+i+"sum:"+driverInfo.getMsgList().size());
        }
        if (receivedMessageEvent.getTakePhotoCommand().equals("takePhoto")) {
            surfaceViewPhoto.setVisibility(View.VISIBLE);
            executors.execute(takePhotoThread);
        }
        if (receivedMessageEvent.getRecordVideo().equals("startRecordVideo")) {
            surfaceViewVideo.setVisibility(View.VISIBLE);
            startVideo();
        }
        if (receivedMessageEvent.getRecordVideo().equals("stopRecordVideo")) {
            stopVideo();
            surfaceViewVideo.setVisibility(View.INVISIBLE);
        }
        if (receivedMessageEvent.getRecordVideo().equals("startRecordVideoTime")) {
            videoTime = receivedMessageEvent.getVideoTime();
            surfaceViewVideo.setVisibility(View.VISIBLE);
            startVideo();
            recordVideoThread.start();
        }
        if (receivedMessageEvent.getRecorder().equals("startRecorder")) {
            startRecorder();
        }
        if (receivedMessageEvent.getRecorder().equals("stopRecorder")) {
            stopRecorder();
        }
    }

    /**
     *  接收提示信息，并用Toast显示
     * @param s
     */
    public void onEventMainThread (String s) {
        ToastUtils.showToast(s);
    }
    /**
     *  通知主线程更新界面 昼夜间
     * @param fare
     */
    public void onEventMainThread (Fare fare) {
        System.out.println("Fare收到更新夜间通知" + fare);
        isNight.setText(TimeUtils.isNight());
    }
    /**
     *  初始化录像参数，开始录像
     */
    public void startVideo() {
        try {
            File videoFile = new File(FileUtils.getVideoDir(), TimeUtils.getMediaTime() + ".mp4");
            mediaRecorder = new MediaRecorder();
            mediaRecorder.reset();
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            mediaRecorder.setVideoSize(320, 240);
            mediaRecorder.setVideoFrameRate(5);
            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
            mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263);
            mediaRecorder.setOutputFile(videoFile.getAbsolutePath());
            mediaRecorder.setPreviewDisplay(surfaceViewVideo.getHolder().getSurface());
            mediaRecorder.prepare();
            mediaRecorder.start();
        } catch (Exception e) {
            logger.error(e);
            e.printStackTrace();
        }
    }

    /**
     *  停止录像
     */
    public void stopVideo() {
        try {
            if (mediaRecorder != null) {
                mediaRecorder.stop();
                mediaRecorder.release();
                mediaRecorder = null;
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
            mediaRecorder.release();
            mediaRecorder = null;
        }
    }

    /**
     *  初始化录音参数，开始录音
     */
    public void startRecorder() {
        try {
            soundFile = new File(FileUtils.getAudioDir(), TimeUtils.getMediaTime() + ".amr");
            mRecorder = new MediaRecorder();
            mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            mRecorder.setOutputFile(soundFile.getAbsolutePath());
            mRecorder.prepare();
            mRecorder.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *  停止录音
     */
    public void stopRecorder() {
        if ((soundFile == null) || (soundFile.exists())) {
            mRecorder.stop();
            mRecorder.release();
            mRecorder = null;
        }
    }

    private final class MyPictureCallback implements PictureCallback {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            try {
                saveToSDCard(data); // 保存图片到SD卡中
                Toast.makeText(getApplicationContext(), "成功拍照", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                logger.error(e);
                e.printStackTrace();
            }
        }
    }

    /**
     *  将拍下来的照片存放在SD卡中
     * @param data 照片流
     */
    public void saveToSDCard(byte[] data) {
        String name = (FileUtils.getPictureDir() + TimeUtils.getMediaTime() + ".jpg");

        FileOutputStream outputStream = null; // 文件输出流
        try {
            outputStream = new FileOutputStream(new File(name));
            outputStream.write(data); // 写入SD卡中
            outputStream.close(); // 关闭输出流
        } catch (IOException e) {
            logger.error("图片保存失败!" + e);
            Toast.makeText(this, "图片保存失败!", Toast.LENGTH_LONG).show();
        }
    }

    private final class SurfaceCallback implements Callback {
        // 拍照状态变化时调用该方法
        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            parameters = camera.getParameters(); // 获取各项参数
            parameters.setPreviewSize(width, height); // 设置预览大小
            parameters.setPictureSize(width, height); // 设置保存的图片尺寸
            parameters.setJpegQuality(80); // 设置照片质量
        }

        // 开始拍照时调用该方法
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            try {
                camera = Camera.open(); // 打开摄像头
                camera.setPreviewDisplay(holder); // 设置用于显示拍照影像的SurfaceHolder对象
                camera.setDisplayOrientation(getPreviewDegree(MainActivity.this));
                camera.startPreview(); // 开始预览
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e);
            }
        }

        // 停止拍照时调用该方法
        @Override
        public void surfaceDestroyed(SurfaceHolder arg0) {
            if (camera != null) {
                camera.release(); // 释放照相
                camera = null;
            }
        }

    }

    /**
     * 提供一个静态方法，用于根据手机方向获得相机预览画面旋转的角度
     * @param activity
     * @return 相机预览画面旋转的角度
     */
    private int getPreviewDegree(Activity activity) {
        // 获得手机的方向
        int rotation = activity.getWindowManager().getDefaultDisplay()
                .getRotation();
        int degree = 0;
        /// 根据手机的方向计算相机预览画面应该选择的角度
        switch (rotation) {
            case Surface.ROTATION_0:
                degree = 90;
                break;
            case Surface.ROTATION_90:
                degree = 0;
                break;
            case Surface.ROTATION_180:
                degree = 270;
                break;
            case Surface.ROTATION_270:
                degree = 180;
                break;
        }
        return degree;
    }

    /**
     *  初始化组件
     */
    private void setTextView() {
        surfaceViewPhoto = ((SurfaceView) findViewById(R.id.take_photo_surfaceView));
        surfaceViewPhoto.getHolder().setFixedSize(800, 480);
        surfaceViewPhoto.getHolder().setKeepScreenOn(true);
        surfaceViewPhoto.getHolder().addCallback(new SurfaceCallback());

        surfaceViewVideo = ((SurfaceView) findViewById(R.id.record_video_surfaceView));
        surfaceViewVideo.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        surfaceViewVideo.getHolder().setFixedSize(176, 144);
        surfaceViewVideo.getHolder().setKeepScreenOn(true);

        imageView = (ImageView) findViewById(R.id.driver_photo);

        money = (TextView) findViewById(R.id.money);
        price = (TextView) findViewById(R.id.price);
        length = (TextView) findViewById(R.id.length);
        time = (TextView) findViewById(R.id.time);
        upTime = (TextView) findViewById(R.id.get_up);
        downTime = (TextView) findViewById(R.id.get_down);

        isNight = (TextView) findViewById(R.id.isNight);
        twoOrOne = (TextView) findViewById(R.id.twoOrOne);
        ic = (TextView) findViewById(R.id.ic);
        stop = (TextView) findViewById(R.id.stop);
        low = (TextView) findViewById(R.id.low);

        thankEvaluate = (TextView) findViewById(R.id.thank_evaluate);

        isNight.setText("");
        twoOrOne.setText("");
        ic.setText("");
        low.setText("");
        stop.setText("");
        twoOrOne.setText("");
        upTime.setText("");
        downTime.setText("");

        companyName = (TextView) findViewById(R.id.company_name);
        companyName.setText(driverInfo.getDriverCompany());
        driverName = (TextView) findViewById(R.id.driver_name);
        driverName.setText(driverInfo.getDriverName());
        licenseNum = (TextView) findViewById(R.id.license_num);
        cardNum = (TextView) findViewById(R.id.card_num);
        cardNum.setText(driverInfo.getICID());
        //inTime = (TextView) findViewById(R.id.in_time);
        //inTime.setText(driverInfo.getInTime());
        telephone = (TextView) findViewById(R.id.tel);
        //message = (TextView) findViewById(R.id.message);
        verticalScrollTV = (AutoVerticalScrollTextView) findViewById(R.id.textview_auto_roll);

        if (driverInfo.getDriverPhoto() == null) {
            System.out.println("FileUtils重新获取照片");
            getDriverPhotoThread.start();
        } else {
            imageView.setImageBitmap(driverInfo.getDriverPhoto());
        }

        initToolbar();
    }

    /**
     * 延时
     * @param time 毫秒
     */
    private void delay(int time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            logger.error(e);
            e.printStackTrace();
        }
    }

    /**
     *  提醒
     * @param s 提醒内容
     */
    private void alert(String s) {
        new AlertDialog.Builder(this).setTitle("警告！！！").setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt) {
            }
        }).setMessage(s).create().show();
    }

    /**
     *  打电话
     * @param phoneNum 电话号码
     */
    private void dial(String phoneNum) {
        startActivity(new Intent("android.intent.action.DIAL", Uri.parse("tel:" + phoneNum)));
    }
    public void initToolbar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//        toolbar.setTitle("");
        TextView textView = (TextView) findViewById(R.id.toolbar_title);
        textView.setText(R.string.app_name);
        textView.setTextColor(getResources().getColor(R.color.black));
        setSupportActionBar(toolbar);
        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if (actionBar != null){
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowTitleEnabled(false);
        }
    }
    /**
     *  返回键响应
     */
    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


}
